/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-08-07
 * Time: 17:45
 */
public class Test {
    //leetcode 704 二分查找
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while(left < right) {
            int mid = left + (right-left) / 2;
            if(nums[mid] > target) {
                right = mid - 1;
            }else if(nums[mid] < target) {
                left = mid;
            }else {
                return mid;
            }
        }
        return -1;
    }

    //leetcode 35 搜索插入位置
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while(left <= right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] > target) {
                right = mid - 1;
            }else if(nums[mid] < target) {
                left = mid + 1;
            }else {
                return mid;
            }
        }
        return right + 1;
    }

    //leetcode 34 在排序数组中查找元素的第一个和最后一个位置
    public int[] searchRange(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int[] ret = {-1,-1};
        int mid = 0;
        while(left <= right) {
            mid = left + (right - left) / 2;
            if(nums[mid] > target) {
                right = mid - 1;
            }else if(nums[mid] < target) {
                left = mid + 1;
            }else {
                break;
            }
        }
        if(left > right) {
            return ret;
        }else {
            int tmp = mid;
            while(tmp >= left) {
                if(nums[tmp] == target) {
                    tmp--;
                }else {
                    break;
                }
            }
            ret[0] = tmp + 1;
            while(mid <= right) {
                if(nums[mid] == target) {
                    mid++;
                }else {
                    break;
                }
            }
            ret[1] = mid - 1;
        }
        return ret;
    }
}
